package com.lujianfei.filesend.ui.server

import android.content.Context
import android.content.Intent
import android.view.View
import com.lujianfei.filesend.R
import com.lujianfei.filesend.base.BaseActivity
import com.lujianfei.filesend.base.toast
import com.lujianfei.filesend.databinding.ActivityServerChatBinding
import com.lujianfei.filesend.ui.server.viewmodel.ServerChatViewModel
import com.lujianfei.filetransfer.TcpManager
import com.lujianfei.filetransfer.TcpMessageListener


/**
 * Author: lujianfei
 * Date: 2023/10/18 15:07
 * Description: 服务端聊天界面
 */

class ServerChatActivity: BaseActivity<ActivityServerChatBinding>(), TcpMessageListener {
    companion object {
        fun start(context: Context, title:String, ipaddress:String) {
            context.startActivity(Intent(context, ServerChatActivity::class.java).putExtra("title", title).putExtra("ipaddress", ipaddress))
        }
    }

    private val viewModel:ServerChatViewModel by lazy { buildViewModel() }
    override fun resourceId() = R.layout.activity_server_chat

    override fun initView() {
        binding?.vm = viewModel
    }

    override fun initData() {
        viewModel.title.set(intent?.getStringExtra("title"))
        viewModel.ipaddress.set(intent?.getStringExtra("ipaddress"))
        TcpManager.instance.addListener(this)
    }

    override fun initEvent() {
        binding?.onBackClick = View.OnClickListener {
            onBackPressed()
        }
        binding?.widgetInputLayout?.onTextSend = {
            viewModel.sendMessage(it)
        }
        viewModel.onScrollToEnd = {
            binding?.recyclerview?.layoutManager?.scrollToPosition(0)
        }
    }

    override fun onDestroy() {
        TcpManager.instance.removeListener(this)
        super.onDestroy()
    }

    override fun onServerStart(address: String, port: Int) {
    }

    override fun onClientAccept(address: String) {
    }

    override fun onClientClose(address: String) {
        viewModel.onClientClose(address) {
            finish()
        }
    }

    override fun onMessageReceive(ip: String, message: String) {
        viewModel.onMessageReceive(ipaddress = ip, message = message)
    }

    override fun onNameAccept(address: String, name: String) {
        viewModel.onNameAccept(ipaddress = address, name = name)
    }

    override fun onConnectFailed(address: String, error: String) {

    }

    override fun onConnectSuccess(address: String) {
    }
}